document.addEventListener('DOMContentLoaded', function() {
    // 模态框元素
    const classModal = document.getElementById('classModal');
    const classModalContent = document.getElementById('classModalContent');
    const deleteClassModal = document.getElementById('deleteClassModal');
    const deleteClassModalContent = document.getElementById('deleteClassModalContent');

    // 按钮元素
    const addClassBtn = document.getElementById('addClassBtn');
    const closeClassModalBtn = document.getElementById('closeClassModal');
    const saveClassBtn = document.getElementById('saveClassBtn');
    const cancelClassBtn = document.getElementById('cancelClassBtn');
    const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');

    // 表单元素
    const classForm = document.getElementById('classForm');
    const classTableBody = document.getElementById('classTableBody');


    // 当前操作的班级ID
    let currentClassId = null;



    function loadTeachers(department = '') {
    const teacherSelect = document.getElementById('headTeacherId');
    teacherSelect.innerHTML = '<option value="">请选择教师</option>'; // 清空原有选项
    fetch(`/admin/course/get_teachers`,methods=['GET']) // 后端API接口，返回教师列表
        .then(response => response.json())
        .then(data => {
            if (data.success && data.teachers.length > 0) {
                data.teachers.forEach(teacher => {
                    const option = document.createElement('option');
                    option.value = teacher.id;
                    // 显示格式：姓名 (工号-院系)
                    option.textContent = `${teacher.username} (${teacher.teacher_no}-${teacher.department})`;
                    teacherSelect.appendChild(option);
                });
            }
        })
        .catch(error => {
            console.error('Error loading teachers:', error);
            showToast('加载教师列表失败', 'error');
        });
}


function loadClassStudents(classId) {
    const monitorSelect = document.getElementById('classMonitor');
    monitorSelect.innerHTML = '<option value="">不指定</option>'; // 清空原有选项
    if (!classId) return; // 新增班级时无班级ID，不加载学生
    fetch(`/admin/class/get_students/${classId}`) // 假设后端提供获取班级学生的API
        .then(response => response.json())
        .then(data => {
            if (data.success && data.students.length > 0) {
                data.students.forEach(student => {
                    const option = document.createElement('option');
                    option.value = student.id;
                    // 显示：学生姓名 (学号)
                    option.textContent = `${student.username} (${student.student_no})`;
                    monitorSelect.appendChild(option);
                });
            }
        })
        .catch(error => {
            console.error('Error loading students:', error);
            showToast('加载学生列表失败', 'error');
        });
}


    // 打开新增班级模态框
    addClassBtn.addEventListener('click', function() {
        currentClassId = null;
        classForm.reset();
        loadTeachers();
        document.getElementById('classModalTitle').textContent = '新增班级';
        openModal(classModal, classModalContent);
    });

    // 关闭班级模态框
    closeClassModalBtn.addEventListener('click', function() {
        closeModal(classModal, classModalContent);
    });

    // 取消新增/编辑
    cancelClassBtn.addEventListener('click', function() {
        closeModal(classModal, classModalContent);
    });

    // 取消删除
    cancelDeleteBtn.addEventListener('click', function() {
        closeModal(deleteClassModal, deleteClassModalContent);
    });

    // 编辑班级
    classTableBody.addEventListener('click', function(e) {
        if (e.target.closest('.edit-class-btn')) {
            const row = e.target.closest('tr');
            currentClassId = row.dataset.classId;
            loadClassStudents(currentClassId);
            loadTeachers()
            // 通过API获取班级详情
            fetch(`/admin/class/get_class/${currentClassId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const classData = data.class;
                        document.getElementById('className').value = classData.class_name;
                        document.getElementById('classMajor').value = classData.major;
                        // 修改：获取年级文本框（原为classGrade，现改为grade）
                        document.getElementById('grade').value = classData.grade || '';
                        document.getElementById('headTeacherId').value = classData.advisor_id || '';
                        document.getElementById('classMonitor').value = classData.monitor_id || '';
                        document.getElementById('classDescription').value = classData.description || '';
                        document.getElementById('classModalTitle').textContent = '编辑班级';
                        openModal(classModal, classModalContent);
                    } else {
                        showToast('获取班级信息失败', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error fetching class:', error);
                    showToast('网络错误，请重试', 'error');
                });
        }
    });

    // 删除班级
    classTableBody.addEventListener('click', function(e) {
        if (e.target.closest('.delete-class-btn')) {
            const row = e.target.closest('tr');
            currentClassId = row.dataset.classId;
            const className = row.querySelector('td:nth-child(2)').textContent;

            document.getElementById('deleteClassName').textContent =
                `你确定要删除班级 "${className}" 吗？`;
            openModal(deleteClassModal, deleteClassModalContent);
        }
    });

    // 确认删除班级
    confirmDeleteBtn.addEventListener('click', function() {
        if (!currentClassId) return;

        fetch(`/admin/class/${currentClassId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 从表格中移除该班级行
                const row = document.querySelector(`tr[data-class-id="${currentClassId}"]`);
                if (row) {
                    // 添加删除动画
                    row.classList.add('opacity-0');
                    setTimeout(() => {
                        row.remove();
                        // 如果表格为空，显示空状态
                        if (classTableBody.children.length === 0) {
                            classTableBody.innerHTML = `
                                <tr>
                                    <td colspan="7" class="px-6 py-12 text-center">
                                        <div class="mb-6">
                                            <i class="fa fa-users text-4xl text-primary/10 animate-spin"></i>
                                        </div>
                                        <h3 class="text-lg font-bold text-gray-800 mb-2">暂无班级记录</h3>
                                        <p class="text-gray-500 mb-6">点击「新增班级」按钮创建新班级</p>
                                    </td>
                                </tr>
                            `;
                        }
                    }, 300);
                }

                showToast('班级删除成功', 'success');
            } else {
                showToast(data.message || '删除失败', 'error');
            }
            closeModal(deleteClassModal, deleteClassModalContent);
        })
        .catch(error => {
            console.error('Error deleting class:', error);
            showToast('网络错误，请重试', 'error');
            closeModal(deleteClassModal, deleteClassModalContent);
        });
    });



    // 保存班级信息
    saveClassBtn.addEventListener('click', function() {
        if (!validateClassForm()) return;

        const formData = new FormData(classForm);
        const url = currentClassId
            ? `/admin/class/update_class/${currentClassId}`
            : '/admin/class/add_class';
        const method = currentClassId ? 'PUT' : 'POST';

        fetch(url, {
            method: method,
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast(currentClassId ? '班级更新成功' : '班级创建成功', 'success');
                closeModal(classModal, classModalContent);

                // 刷新页面（服务器端渲染）
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                showToast(data.message || '操作失败', 'error');
            }
        })
        .catch(error => {
            console.error('Error saving class:', error);
            showToast('网络错误，请重试', 'error');
        });
    });



    // 表单验证
    function validateClassForm() {
        const className = document.getElementById('className').value.trim();
        const classMajor = document.getElementById('classMajor').value.trim();
        // 修改：获取年级文本框（原为classGrade，现改为grade）
        const classGrade = document.getElementById('grade').value.trim();
        const headTeacherId = document.getElementById('headTeacherId').value;

        if (!className) {
            showToast('请输入班级名称', 'error');
            return false;
        }

        if (!classMajor) {
            showToast('请输入所属专业', 'error');
            return false;
        }

        // 修改：验证年级文本框
        if (!classGrade) {
            showToast('请输入年级', 'error');
            return false;
        }

        // 验证年级是否为1-6的数字
        const gradeNum = parseInt(classGrade, 10);
        if (isNaN(gradeNum) || gradeNum < 1 || gradeNum > 6) {
            showToast('年级必须为1-6的数字', 'error');
            return false;
        }

        if (!headTeacherId) {
            showToast('请选择班主任', 'error');
            return false;
        }

        return true;
    }

    // 打开模态框动画
    function openModal(modal, content) {
        modal.classList.remove('opacity-0', 'pointer-events-none');
        setTimeout(() => {
            content.classList.remove('scale-95');
            content.classList.add('scale-100');
        }, 10);
    }

    // 关闭模态框动画
    function closeModal(modal, content) {
        content.classList.remove('scale-100');
        content.classList.add('scale-95');
        setTimeout(() => {
            modal.classList.add('opacity-0', 'pointer-events-none');
        }, 300);
    }

    // 显示提示消息
    function showToast(message, type = 'info') {
        // 检查是否已存在toast容器
        let toastContainer = document.getElementById('toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.id = 'toast-container';
            toastContainer.className = 'fixed top-4 right-4 z-50 flex flex-col gap-3';
            document.body.appendChild(toastContainer);
        }

        // 创建toast元素
        const toast = document.createElement('div');
        toast.className = `px-4 py-3 rounded-lg shadow-lg transform transition-all duration-300 opacity-0 translate-y-2 flex items-center gap-3 ${
            type === 'success' ? 'bg-green-50 border border-green-200 text-green-700' :
            type === 'error' ? 'bg-red-50 border border-red-200 text-red-700' :
            'bg-blue-50 border border-blue-200 text-blue-700'
        }`;

        toast.innerHTML = `
            <i class="fa ${
                type === 'success' ? 'fa-check-circle' :
                type === 'error' ? 'fa-exclamation-circle' :
                'fa-info-circle'
            }"></i>
            <span>${message}</span>
        `;

        // 添加到容器
        toastContainer.appendChild(toast);

        // 显示动画
        setTimeout(() => {
            toast.classList.remove('opacity-0', 'translate-y-2');
        }, 10);

        // 3秒后隐藏
        setTimeout(() => {
            toast.classList.add('opacity-0', 'translate-y-2');
            setTimeout(() => {
                toast.remove();
                // 如果容器为空，移除容器
                if (toastContainer.children.length === 0) {
                    toastContainer.remove();
                }
            }, 300);
        }, 3000);
    }
});